package com.adopapa.ethexplorer.service;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.adopapa.ethexplorer.domain.BlockInfo;
import com.adopapa.ethexplorer.domain.BlockInfoRespsoitory;
import com.adopapa.ethexplorer.utils.Tools;

@Service
public class BlockInfoService extends BaseService {

	@Autowired
	private BlockInfoRespsoitory blockInfoRespsoitory;

	public BlockInfo getBlockInfoById(String id) {
		Optional<BlockInfo> optional = blockInfoRespsoitory.findById(id);
		return optional.isPresent() ? optional.get() : null;
	}

	public BlockInfo getBlockInfoByNumber(Long number) {
		List<BlockInfo> results = blockInfoRespsoitory.findByNumber(number);
		return Tools.empty(results) ? null : results.get(0);
	}

	public BlockInfo getBlockInfoByHash(String hash) {
		List<BlockInfo> results = blockInfoRespsoitory.findByHash(hash);
		return Tools.empty(results) ? null : results.get(0);
	}

	public BlockInfo getLastBlockInfo() {
		Page<BlockInfo> page = getBlockInfoPage(1, 1, new BlockInfo());
		return Tools.empty(page.getContent()) ? null : page.getContent().get(0);
	}

	public Page<BlockInfo> getBlockInfoPage(int pageNo, int pageSize, BlockInfo blockInfo) {
		PageRequest pageRequest = QueryHelper.buildPageRequest(pageNo, pageSize, Order.desc("number"));
		Specification<BlockInfo> specification = QueryHelper.buildSpecification(blockInfo);
		Page<BlockInfo> page = blockInfoRespsoitory.findAll(specification, pageRequest);
		return page;
	}
	

	public BlockInfo saveBlockInfo(BlockInfo blockInfo) {
		return blockInfoRespsoitory.saveAndFlush(blockInfo);
	}

	public List<BlockInfo> saveBlockInfos(List<BlockInfo> blockInfos) {
		return blockInfoRespsoitory.saveAllAndFlush(blockInfos);
	}

	public void delete(String id) {
		blockInfoRespsoitory.deleteById(id);
	}

	public void delete(BlockInfo blockInfo) {
		blockInfoRespsoitory.delete(blockInfo);
	}

}
